<template>
  <div>
    <div style="margin:30px auto;width: 1200px;display: flex;flex-direction: column;background-color: white">
<!--      标签页-->
      <el-tabs v-model="activeName" @tab-click="handleClick" style="margin: 10px 20px;">
<!--        资料设置标签页-->
        <el-tab-pane label="资料设置" name="first">
          <p style="font-size: 13px;color:#999999;">绝不会以任何形式向第三方透漏你的身份信息</p>
<!--          个人信息表单-->
          <el-form :model="userData" :rules="rules" ref="userForm" label-position=left label-width="90px"
                   style="width: 460px;margin-left: 30px">
            <el-form-item label="头像" prop="avatar">
              <el-upload
                  class="avatar-uploader"
                  action="http://localhost:8089/uploadFile"
                  :show-file-list="false"
                  :on-success="afterFileUpload"
                  style="margin-left: 40px"
              >
                <img v-if='userData.avatar!=null' :src='`http://localhost:8089/upload/${userData.avatar}`'
                     class="avatar"/>
                <el-avatar v-else icon="el-icon-user-solid" :size="104"
                           style="font-size: 48px;text-align: center;"></el-avatar>
                <span style="position: absolute;left: 65px;top: 65px;color: white">编辑头像</span>
              </el-upload>
            </el-form-item>
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="userData.userName"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <div v-if="!updateFlag">
                <a>{{ userData.email }}</a>
                <a @click="on_updateEmailBut" style="margin-left: 20px;cursor:pointer;">修改邮箱</a>
              </div>
              <div v-if="updateFlag">
                <el-input v-model="userData.email" style="width: 50%"></el-input>
                <el-button type="primary" @click="codeVisible=true" style="margin-left:5px;width: 22%">保 存</el-button>
                <el-button @click="on_cancelUpdate" style="width: 22%">取 消</el-button>
              </div>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userData.phone"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="userData.sex">
                <el-radio :label=1>男</el-radio>
                <el-radio :label=2>女</el-radio>
                <el-radio :label=3>其他</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                  v-model="userData.birthday"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="身份类型" prop="identitytypeId">
              <el-radio-group v-model="userData.identitytypeId">
                <el-radio :label=1>学生</el-radio>
                <el-radio :label=2>在职</el-radio>
                <el-radio :label=3>其他</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="最高学历" prop="degreeId">
              <div style="display: flex;flex-direction: column;width: 340px">
                <el-radio-group class="radio-group" v-model="userData.degreeId">
                  <el-radio class="radio-item" :label=1>博士</el-radio>
                  <el-radio class="radio-item" :label=2>研究生</el-radio>
                  <el-radio class="radio-item" :label=3>本科</el-radio>
                  <el-radio class="radio-item" :label=4>专科</el-radio>
                </el-radio-group>
                <el-radio-group class="radio-group" v-model="userData.degreeId" style="margin-top: 10px">
                  <el-radio class="radio-item" :label=5>高中</el-radio>
                  <el-radio class="radio-item" :label=6>初中</el-radio>
                  <el-radio class="radio-item" :label=7>小学</el-radio>
                  <el-radio class="radio-item" :label=8>其他</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
            <el-form-item label="个人简介" prop="biography">
              <el-input type="textarea" :autosize="{ minRows: 4}" placeholder="介绍一下自己吧"
                        v-model="userData.biography"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateUser" :disabled="updateFlag">保 存</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
<!--      修改邮箱，验证码验证对话框-->
      <el-dialog
          :visible.sync="codeVisible"
          width="30%"
          top="300px"
          center>
        <el-form :model="userData" :rules="rules" ref="emailFrom" style="width: 70%;margin-left: 75px">
          <p style="text-align: center;width: 100%;font-size: 20px">修改邮箱</p>
          <el-form-item prop="code">
            <el-input v-model="userData.code" autocomplete="off" placeholder="请输入验证码"
                      style="width: 350px;height: 46px;margin:10px 0">
              <i slot="prefix" class="el-input__icon el-icon-lock" style="font-size: 24px"></i>
            </el-input>
            <button @click.prevent="getCode()"  class="code-btn" style="right: 16px" :disabled="!showCode">
              <span v-show="showCode">获取验证码</span>
              <span v-show="!showCode" class="count">{{count}} s</span>
            </button>
          </el-form-item>
          <el-form-item style="text-align: center">
            <el-button type="primary" style="width: 300px" @click="updateEmail">确 定 修 改</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: "UserSetting",
  data() {
    return {
      userData: {},
      activeName: 'first',
      updateFlag: false,
      email: '',
      showCode:true,
      codeVisible:false,
      count:'',
      defaultImg: 'this.src = "' + require('../assets/logo.png') + '"',
      rules: {
        phone: [
          {required: true, message: '手机号不能为空', trigger: 'blur'},
          {pattern: /^[0-9]{11}$/, message: '请输入正确的手机号', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'},
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            message: '请输入正确的邮箱',
            trigger: 'blur'
          }
        ],
        userName: [
          {required: true, message: '用户名不能为空', trigger: 'blur'}
        ],
        identitytypeId: [
          {required: true, message: '请选择您的身份类型', trigger: 'blur'}
        ],
        degreeId: [
          {required: true, message: '请选择您的最高学历', trigger: 'blur'}
        ],
        code:[
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {pattern: /^[0-9]{6}$/, message: '验证码应是6位数字', trigger: 'blur'}
        ]
      },
    }
  },
  methods: {
    // 获取用户信息
    getUserData(userId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/user/selectUserAllById/${userId}`,
      }).then(res => {
        if (res.data.code === 200) {
          this.userData = res.data.dataobject;
        } else {
          this.$router.push("/#/");
        }
      }).catch(err => console.log(err));
    },
    // 修改用户信息
    updateUser() {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: "http://localhost:8089/user/updateUser",
            data: this.userData
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success("保存用户信息成功")
              localStorage.setItem('userName', this.userData.userName)
              localStorage.setItem('avatar', this.userData.avatar)
              setTimeout(() =>
                      this.$router.go(0)
                  , 1000)
            } else {
              this.$message.error(res.data.msg)
            }
          }).catch(err => console.log(err));
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 修改邮箱信息
    updateEmail(){
      this.$refs["emailFrom"].validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: "http://localhost:8089/user/updateEmail",
            data: {"userId":this.userData.userId,"email":this.userData.email,"code":this.userData.code}
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success("修改邮箱成功")
              this.updateFlag=false
              this.codeVisible=false
            } else {
              this.$message.error(res.data.message)
            }
          }).catch(err => console.log(err));
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 获取发送邮箱验证码的检验码
    getCode() {
      this.$axios({
        method:'post',
        url:'http://localhost:8089/code/request',
        data:{"email":this.userData.email}
      }).then(res=>{
        localStorage.setItem('permissionCode',res.data.data.permissionCode);
      }).catch(err=>console.log(err));
      setTimeout(()=>this.getEmailCode(),500)
    },
    // 发送邮箱验证码
    getEmailCode(){
      this.$axios({
        method: 'post',
        url: 'http://localhost:8089/code/email',
        data: {"email": this.userData.email, "code": localStorage.getItem('permissionCode')}
      }).then(res=>{
        if(res.data.code===200) {
          this.$message.success("发送验证码成功")
          if (!this.timer) {
            this.count = 60;
            this.showCode = false;
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= 60) {
                this.count--;
              } else {
                this.showCode = true;
                clearInterval(this.timer);
                this.timer = null;
              }
            }, 1000);
          }
        }
        else{
          this.$message.error(res.data.message);
        }
      }).catch(err=>console.log(err))
    },
    //文件上传前
    beforeAvatarUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isImage) {
        this.$message.error('上传图片只能是JPG、png、Webp格式！');
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过10MB!');
      }
      return isImage && isLt10M;
    },
    //文件上传之后
    afterFileUpload(response, file) {
      console.log(response);
      this.userData.avatar = response.dataobject;
    },
    on_updateEmailBut() {
      this.updateFlag = true;
      this.email = this.userData.email;
    },
    on_cancelUpdate() {
      this.userData.email = this.email;
      //单独取消email输入框的校验
      this.$refs['userForm'].clearValidate('email')
      this.updateFlag = false;
    },
  },
  created() {
    if (localStorage.getItem('token') != null) {
      this.getUserData(localStorage.getItem('userId'));
    }
  }
}
</script>

<style scoped>
/deep/ .el-tabs__item {
  font-size: 16px !important;
  color: #333333 !important;
  margin-bottom: 5px !important;
}

.radio-group {
  display: flex;
}

.radio-item {
  width: 25%;
}

.avatar {
  width: 104px;
  height: 104px;
  border-radius: 50%;
}
</style>